﻿using Anke.SHManage.BLL;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace Anke.SHManage.Web.Areas.PR.Controllers
{
    public class HistoricalPatientController : Controller
    {
        //
        // GET: /PR/HistoricalPatient/


        public ActionResult HistoricalPatientInfo(string CallPhone, string PatientName, string tokenkey)//2022-10-19 add lxh
        {
            var StartTime = DateTime.Now.AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
            var EndTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            this.ViewData["StartTime"] = StartTime;
            this.ViewData["EndTime"] = EndTime;
            this.ViewData["CallPhone"] = CallPhone;
            this.ViewData["PatientName"] = PatientName;
            //if (GetApiAuth(tokenkey)) //zll
            return View();
            //else
            //    return Json(new { status = 0, message = "token验证失败", result = "" }, "appliction/json", JsonRequestBehavior.AllowGet);

        }

        public ActionResult DataLoad()
        {
            //获取页容量
            int pageSize = int.Parse(Request.Form["rows"]);
            //获取请求的页码
            int pageIndex = int.Parse(Request.Form["page"]);
            //获取查询条件
            DateTime start = Convert.ToDateTime(Request.Form["StartTime"]);
            DateTime end = Convert.ToDateTime(Request.Form["EndTime"]);
            string CallPhone = Request.Form["CallPhone"].ToString();
            string PatientName = Request.Form["PatientName"].ToString();

            //添加SQL防注入，参考plq  20221018 lxh add
            if (ControlHelper.ProcessSqlStr(start.ToString()) && ControlHelper.ProcessSqlStr(end.ToString())
              && ControlHelper.ProcessSqlStr(CallPhone) && ControlHelper.ProcessSqlStr(PatientName))
            {
                try
                {
                    #region 拼接查询条件
                    Expression<Func<M_PatientRecord, bool>> where = p => p.MedicalRecordGenerationTime >= start && p.MedicalRecordGenerationTime <= end;
                    if (!string.IsNullOrEmpty(CallPhone))
                    {
                        where = where.And(pr => pr.ForHelpTelephone.Contains(CallPhone));//呼叫电话
                    }
                    if (!string.IsNullOrEmpty(PatientName))
                    {
                        where = where.And(pr => pr.Name.Contains(PatientName));
                    }
                    #endregion
                    Expression<Func<M_PatientRecord, dynamic>> templist = p => new { p.TaskCode, p.PatientOrder, p.PatientVersion, p.SubmitLogo, p.MedicalRecordGenerationTime, p.Name, p.ContactTelephone };
                    int total = 0;
                    var infoList = new M_PatientRecordBLL().GetDynamicPagedList(pageIndex, pageSize, ref total, where, u => u.MedicalRecordGenerationTime, templist, false).ToList();
                    return Json(new { total = total, rows = infoList }, "appliction/json", JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    LogUtility.Error("HistoricalPatientController/DataLoad()", ex.ToString());
                    return this.Json("");
                }
            }
            else
            {
                return Json(new { total = 0, rows = "dangerousInfomation" }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }
        public void HistoricalPatientPrint(string AlarmEventType, string TaskCode, int PatientOrder, string SubmitLogo)
        {
            string aspxUrl = "~/Reports/PrintModeWebForm.aspx?AlarmEventType=" + Server.UrlEncode(AlarmEventType);
            aspxUrl += "&TaskCode=" + TaskCode;
            aspxUrl += "&PatientOrder=" + PatientOrder;
            aspxUrl += "&SubmitLogo=" + SubmitLogo;
            Response.Redirect(aspxUrl);
        }

        /// <summary>
        /// 获取Token
        /// add2022-08-26 plq
        /// </summary>
        /// <returns></returns>
        //[SkipLoginAttribute]
        //public ActionResult GetToken(string workCode, string password)
        //{
        //    string token = "";
        //    try
        //    {
        //        //HashEncrypt hashEncrypt = new HashEncrypt();
        //        //生成Token，作为参数传递---存储当前用户信息实体--第三方客户端调取我方提供接口进行解密，然后验证用户信息
        //        TokenInfo t = new TokenInfo();
        //        t.UserName = "";
        //        t.WorkCode = workCode;
        //        t.LoginName = "";
        //        t.UserPwd = password;
        //        //t.UserPwd = hashEncrypt.DESDecrypt(password, ""); //将库里存的用户密码进行解密

        //        //string token = "";
        //        token = CommonToken.GetToken(t); //获取Token
        //        if (token != "")
        //        {
        //            // return token;
        //            return Json(new { status = 1, token = token, message = "" }, "appliction/json", JsonRequestBehavior.AllowGet);
        //        }
        //        else
        //        {

        //            return Json(new { status = 0, token = token, message = "Token获取失败" }, "appliction/json", JsonRequestBehavior.AllowGet);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        return Json(new { status = 0, token = token, message = ex.Message }, "appliction/json", JsonRequestBehavior.AllowGet);
        //    }
        //}







        // 使用明参方式对于第三方比较简单容易实现。
        [HttpGet]
        public Boolean GetApiAuth(string token)
        {
            Response.Headers.Add("Access-Control-Allow-Origin", "*"); //允许跨域访问
            var sendToken = token;
            try
            {
                if (sendToken == null)
                {
                    return false;
                    //return Json(new { status = 0, message = "InvalidToken", result = "" }, "appliction/json", JsonRequestBehavior.AllowGet);
                }

                //url获取token 
                var now = Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + 5);//当前的时间戳
                var dictPayload = DecodeToken(sendToken);

                if (dictPayload == null)
                {
                    return false;
                    //return Json(new { status = 0, message = "InvalidToken", result = "" }, "appliction/json", JsonRequestBehavior.AllowGet);
                }
                double iat = dictPayload["iat"];
                double exp = dictPayload["exp"];
                //检查令牌的有效期
                if (!(iat <= now && now <= exp))//如果当前时间戳不在Token声明周期范围内，则返回Token过期
                {
                    return false;
                    // return Json(new { status = 0, message = "TokenTimeout", result = "" }, "appliction/json", JsonRequestBehavior.AllowGet);
                }
                //获取Token的自定义键值对
                TokenDecodeUserInfo tokenInfo = new TokenDecodeUserInfo();
                //int UserId = dictPayload["UserId"];
                string UserName = dictPayload["UserName"];
                string WorkCode = dictPayload["WorkCode"];
                string LoginName = dictPayload["LoginName"];
                string UserPwd = dictPayload["UserPwd"];
                tokenInfo.UserName = UserName;
                tokenInfo.WorkCode = WorkCode;
                tokenInfo.LoginName = LoginName;
                tokenInfo.UserPwd = UserPwd;

                string result = JsonHelper.Obj2JsonStr(tokenInfo); //将对象转为JSON字符串
                return true;
                //return Json(new { status = 1, message = "Success", result = result }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return false;
                //return Json(new { status = 0, message = ex.Message, result = "" }, "appliction/json", JsonRequestBehavior.AllowGet);
            }

        }

        /// <summary>
        /// 解Token
        /// 返回字典 [""]方式解析
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        private static IDictionary<string, dynamic> DecodeToken(string token)
        {
            try
            {
                var dictPayload = JWT.JsonWebToken.DecodeToObject(token, CommonToken.SecretKey) as IDictionary<string, dynamic>;
                return dictPayload;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

    }
}
